//
// chat_message.hpp
// ~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2010 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//

#ifndef CHAT_MESSAGE_HPP
#define CHAT_MESSAGE_HPP

#include <boost/cstdint.hpp>

#include <cstdio>
#include <cstdlib>
#include <cstring>

class chat_message
{
public:
  enum { header_minus_ctrl_length = 4 };
  enum { channel_length = sizeof(uint32_t) };
  enum { header_length = header_minus_ctrl_length + channel_length };
  enum { max_body_length = 4096 };

  chat_message()
    : body_length_(0)
  {
  }

  const char* data() const
  {
    return data_;
  }

  char* data()
  {
    return data_;
  }

  size_t length() const
  {
    return header_length + body_length_;
  }

  const char* body() const
  {
    return data_ + header_length;
  }

  char* body()
  {
    return data_ + header_length;
  }

   uint32_t channel() const
   {
      return channel_;
   }

   void channel(uint32_t ctrl)
   {
      channel_ = ctrl;
   }

  size_t body_length() const
  {
    return body_length_;
  }

  void body_length(size_t length)
  {
    body_length_ = length;
    if (body_length_ > max_body_length)
      body_length_ = max_body_length;
  }

      bool decode_header()
      {

         using namespace std; // For strncat and atoi.
         char header_first[header_minus_ctrl_length + 1] = "";
         strncat(header_first, data_, header_minus_ctrl_length);
         body_length_ = atoi(header_first);
         char header_second[sizeof(uint32_t) + 1] = "";
         strncat(header_second, data_ + header_minus_ctrl_length, channel_length);
         channel_ = atoi(header_second);
         if (body_length_ > max_body_length)
         {
            body_length_ = 0;
            return false;
         }
         return true;
      }

      void encode_header()
      {
         using namespace std; // For sprintf and memcpy.
         char header[header_minus_ctrl_length + 1] = "";
         sprintf(header, "%4d", body_length_);
         char ctrl[channel_length + 1] = "";
         sprintf(ctrl, "%4d", channel_);
         memcpy(data_, header, header_minus_ctrl_length);
         memcpy(data_ + header_minus_ctrl_length, ctrl, channel_length);
         std::cout << "data = " << data_ << std::endl;
      }

   private:
      char data_[header_length + max_body_length];
      uint32_t channel_;
      size_t body_length_;
   };

#endif // CHAT_MESSAGE_HPP

